package org.tnaggs.project.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.tnaggs.project.model.Contact;

public class ContactRepository implements GenericRepository<Contact> {
	
	
	private JdbcTemplate template;
	
	public ContactRepository(JdbcTemplate template) {
		this.setTemplate(template);
	}

	public JdbcTemplate getTemplate() {
		return template;
	}

	public void setTemplate(JdbcTemplate template) {
		this.template = template;
	}

	@Override
	public Contact findByID(int id) {
		return (Contact)template.queryForObject("select * from Contact where Contact_ID = " + id, new ContactRowMapper());
	}
	
	@Override
	public List<Contact> findAll() {
		return (List<Contact>)template.query("select * from Contact", new ContactRowMapper());
	}
	
	class ContactRowMapper implements RowMapper<Contact> {

		@Override
		public Contact mapRow(ResultSet rs, int arg1) throws SQLException {
		
				Contact results = new Contact();
				results.setContactID(rs.getInt("Contact_ID"));
				results.setEmail(rs.getString("email"));
				results.setPhoneNumber(rs.getString("phone"));
				results.setLastName(rs.getString("Last_name"));
				results.setFirstName(rs.getString("First_name"));
				results.setPassword(rs.getString("password"));
				results.setRoleID(rs.getInt("Role"));
				return results;
		}

		
		
	}


	@Override
	public boolean insert(Contact newVal) {
		int numResults = template.update("insert into Contact (`Last_name`,`First_name`,`email`,`phone`,`password`,`Role`) values('" 
			    + newVal.getLastName() + "','" + newVal.getFirstName() + "','" + newVal.getEmail() 
				+ "','" + newVal.getPhoneNumber() + "','" + newVal.getPassword() + "'," + newVal.getRoleID() + ")");
		return numResults == 1;
	}

	@Override
	public boolean delete(int id) {
		int numResults =  template.update("delete from Contact where Contact_ID = " + id);
		return numResults == 1;
	}

	@Override
	public boolean purge() {
      int numResults = template.queryForInt("select count(*) from Contact;");
      int delResults = template.update("delete from Contact;");
      return numResults == delResults;
	}

	public Contact findByName(String username) {
		return (Contact)template.queryForObject("select * from Contact where Email = '" + username + "'", new ContactRowMapper());
	}

	public void updatePassword(int contactID, String secondAttempt) {
		template.update("update Contact set Password ='" + secondAttempt +"' where Contact_ID='" + contactID +"'");
	}
}
